<?php

/**
 * contact : 刘经理 19326416371
 * company : 版权所属 四川北星惯牌科技有限公司
 **/

namespace app\admin\command\Project;

use app\common\constant\Constant;
use app\common\model\Match;
use app\common\model\Member;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use think\Exception;

class MatchEnd extends Command
{
    protected $model = null;

    protected function configure()
    {
        $this->setName('match_end')
            ->setDescription('task');
        //要执行的controller必须一样，不适用模糊查询
    }

    protected function execute(Input $input, Output $output)
    {
        $redis = new \Redis();
        $config = config('redis');
        $redis->pconnect($config['host'],$config['port']);

        if ($config['password']){
            $redis->auth($config['password']);
        }
        while (true){

            $matchId = $redis->rPop(Constant::getEndMatchListKey($config['prefix']));
            if ($matchId){
                $memberInfo = Member::where('match_id', $matchId)->field('id,score')->select();
                $data = [];
                if ($memberInfo){
                    foreach ($memberInfo as $k=>$v){
                        $data[$v['id']] = $v['score'];
                    }
                }

                if($data){
                    $ranked = ranks($data);
                    if ($ranked){
                        Db::startTrans();
                        try {
                            foreach ($ranked as $key=>$val) {
                                Member::where('id',$key)->update(['ranks'=>$val,'update_time'=>time()]);
                            }
                            Db::commit();
                        }catch (Exception $e){
                            Db::rollback();
                            echo $e->getMessage();
                        }

                    }
                }
            }

            sleep(10);
        }
    }

}
